package me.zhengjie.modules.weixin.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.config.constant.WeChatConstant;
import me.zhengjie.config.entity.ResponseBaseEntity;
import me.zhengjie.config.enums.AtmrErrorEnum;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.modules.weixin.service.IWechatOAuthService;
import me.zhengjie.request.ATMRContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

@RestController
@RequestMapping("wechat/qrcode")
@Api(tags = "WEB二维码")
public class WechatQrCodeController {

    @Autowired
    private IWechatOAuthService wechatOAuthService;
    private Graphics2D g = null;

    @RequestMapping("generate")
    @ApiOperation("WEB-生成微信用户个人专属码")
    public ResponseBaseEntity generate(String openId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (StringUtils.isBlank(openId)) {
                throw new WeChatException("openId is blank");
            }
            String scene = WeChatConstant.QrCodeScenePrefix + openId;
            System.out.println("scene==============" + scene);
            String wxUserInfo = wechatOAuthService.generate(scene);
            System.out.println("=========================" + wxUserInfo);
            //base64转BufferedImage
            BufferedImage ma = loadImageLocal(wxUserInfo);
            BufferedImage bg = loadImageLocal("http://wx.drzh-atmr.cn/atmr_pst/atmr_pst/pages/images/ewm1.jpg");
            System.out.println("=========================change OK");
            BufferedImage bgImage = resize(bg, 750, 1334);
            BufferedImage resultImage = modifyImagetogeter(bgImage, ma);
            System.out.println("=========================add OK");
            //将多张图片合在一起
            System.out.println("success");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(resultImage, "jpg", outputStream);
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encodeBuffer(outputStream.toByteArray()).trim();
            base64 = base64.replaceAll("\n", "").replaceAll("\r", "");
//            response.setBody(wxUserInfo);
            response.setBody("data:image/jpg;base64," + base64);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @RequestMapping("pushCode")
    @ApiOperation("WEB-生成微信用户个人推广码")
    public ResponseBaseEntity pushCode() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)) {
                throw new WeChatException("openId is blank");
            }
            String scene = WeChatConstant.QrCodeScenePrefix + openId;
            System.out.println("scene==============" + scene);
            String wxUserInfo = wechatOAuthService.generate(scene);
            System.out.println("=========================" + wxUserInfo);
            response.setBody(wxUserInfo);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @GetMapping("pushCodeNew")
    @ApiOperation("WEB-生成微信用户个人推广码New")
    public ResponseBaseEntity pushCodeNew() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)) {
                throw new WeChatException("openId is blank");
            }
            String scene = WeChatConstant.QrCodeScenePrefix + openId;
            System.out.println("scene==============" + scene);
            String wxUserInfo = wechatOAuthService.generate(scene);
            System.out.println("=========================" + wxUserInfo);
            BufferedImage ma = loadImageLocal(wxUserInfo);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(ma, "jpg", outputStream);
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encodeBuffer(outputStream.toByteArray()).trim();
            base64 = base64.replaceAll("\n", "").replaceAll("\r", "");
            response.setBody("data:image/jpg;base64," + base64);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public BufferedImage modifyImagetogeter(BufferedImage bgImage, BufferedImage ma) {

        try {
            int w = ma.getWidth();
            int h = ma.getHeight();
            g = bgImage.createGraphics();
            g.drawImage(ma, 170, 640, w, h, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return bgImage;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);

                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
        Graphics2D g = dimg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
        g.dispose();
        return dimg;
    }

    /**
     * base64 编码转换为 BufferedImage
     *
     * @param base64
     * @return
     */
    private static BufferedImage base64ToBufferedImage(String base64) {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
